const { exec } = require("../core/DBHelper");
const md5 = require("md5");
const fs = require("fs");
const jwt = require("../middleware/authcheck");
const path = require("path");
const CONSTANT = require("../constant");

class AccountController {
  async Login(req, resp, next) {
    //1.得到前端发送过来的用户名和密码
    let newPwd = md5(
      md5(req.body.password) +
        fs.readFileSync(
          path
            .join(__dirname, "../middleware/keys/rsa_private_key.pem")
            .toString()
        )
    );
    let params = [req.body.username, newPwd];
    //2.准备sql语句
    //3.执行sql语句得到结果
    try {
      let result = await exec(CONSTANT.LOGIN_SQL, params);
      let isLogin = result.length >= 1;
      //如果查询的数据大于等于1,就可以删除密码,否则什么都不干

      //判断登录成功,才生成token
      let token = "";
      if (isLogin) {
        delete result[0].password;
        token = jwt.buildToken(result[0]);
      }
      resp.json({
        msg: isLogin ? "登录成功" : "登录失败",
        code: isLogin ? 1 : -1,
        data: result[0], //登录人的信息
        token,
      });
    } catch (error) {
      resp.json({
        msg: "登录失败",
        code: -2,
      });
    }
  }
  async Register(req, resp, next) {
    //1.准备参数

    let newPwd = md5(
      md5(req.body.password) +
        fs.readFileSync(
          path
            .join(__dirname, "../middleware/keys/rsa_private_key.pem")
            .toString()
        )
    );
    let params = [
      req.body.username,
      newPwd,
      req.body.gender,
      req.body.birthday,
    ];
    //2.准备注册的sql语句
    //3.执行sql语句,判断结果
    try {
      let result = await exec(CONSTANT.REIGSTER_SQL, params);
      let isReg = result.affectedRows >= 1;

      resp.json({
        msg: isReg ? "注册成功!" : "注册失败",
        code: isReg ? 1 : -1,
      });
    } catch (error) {
      resp.json({
        msg: "注册失败",
        code: -2,
        error,
      });
    }
  }
}

module.exports = new AccountController();
